import service from "./request";
import qs from "qs";

const _post = (api, data, headers = {}) => {
  return new Promise((resolve, reject) => {
    service
      .post(api, data, { headers })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error.data);
      });
  });
};

const post = (api, data, headers = {}) => {
  headers["Content-Type"] = "application/x-www-form-urlencoded";
  // qs.stringify()作用是将对象或者数组序列化成URL的格式
  return _post(api, qs.stringify(data), headers);
};

const postJson = (api, data, headers = {}) => {
  headers["Content-Type"] = "application/json;charset=utf-8";
  return _post(api, JSON.stringify(data), headers);
};

const postFormData = (api, data, headers = {}) => {
  headers["Content-Type"] = "multipart/form-data";
  return _post(api, data, headers);
};

const get = (api, params = {}, headers = {}) => {
  return new Promise((resolve, reject) => {
    service
      .get(api, { params, headers })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error.data);
      });
  });
};

export default { post, postJson, postFormData, get };
